package com.supplychain.scm.core.http.client.config;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;

/**
 * @author liyang
 * @version 1.0.0
 * @ClassName OkHttpAutoConfiguration
 * @createTime 14:20:00 2023/01/10
 */
@Slf4j
@RequiredArgsConstructor
@RefreshScope
@ConditionalOnClass({OkHttpClient.class})
@ConditionalOnProperty(prefix = OkHttpProperties.PREFIX, name = "enabled", havingValue = "true")
@EnableConfigurationProperties({OkHttpProperties.class})
public class OkHttpAutoConfiguration {

    private final OkHttpProperties okHttpProperties;

    @Bean
    @ConditionalOnMissingBean
    public X509TrustManager x509TrustManager() {
        return new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s) {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        };
    }

    @Bean
    @ConditionalOnMissingBean
    public SSLSocketFactory sslSocketFactory(X509TrustManager x509TrustManager) {
        try {
            //信任任何链接
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[]{x509TrustManager}, new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            log.warn("SSLSocketFactory error => {}", ExceptionUtils.getStackTrace(e));
        }
        return null;
    }

    /**
     * Create a new connection pool with tuning parameters appropriate for a single-user application.
     * The tuning parameters in this pool are subject to change in future OkHttp releases. Currently
     */
    @Bean
    @ConditionalOnMissingBean
    public ConnectionPool connectionPool() {
        return new ConnectionPool(okHttpProperties.getMaxIdleConnections(), okHttpProperties.getKeepAliveDuration(), TimeUnit.SECONDS);
    }

    @Bean
    @ConditionalOnMissingBean({OkHttpClient.class})
    public OkHttpClient okHttpClient(SSLSocketFactory sslSocketFactory,X509TrustManager x509TrustManager,ConnectionPool connectionPool) {
        return new OkHttpClient.Builder()
                .sslSocketFactory(sslSocketFactory, x509TrustManager)
                //是否开启缓存
                //当连接失败，尝试重连
                .retryOnConnectionFailure(okHttpProperties.getPool().isRetryOnConnectionFailure())
                //连接池
                .connectionPool(connectionPool)
                .connectTimeout(okHttpProperties.getPool().getConnectTimeout(), TimeUnit.SECONDS)
                .readTimeout(okHttpProperties.getPool().getReadTimeout(), TimeUnit.SECONDS)
                .writeTimeout(okHttpProperties.getPool().getWriteTimeout(), TimeUnit.SECONDS)
                .hostnameVerifier((hostname, session) -> okHttpProperties.getPool().isHostnameVerifier())
                // 设置代理
                //.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8888)))
                // 拦截器
                //.addInterceptor()
                .build();
    }
}
